<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-lx-cascades"></i> 岗位管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" icon="el-icon-delete" class="handle-del mr10" @click="delAllSelection">批量删除 </el-button>
                <el-button type="primary" icon="el-icon-plus" class="handle-del mr10" @click="handleAdd">
                    添加岗位
                </el-button>
                <el-button type="primary" icon="el-icon-download" class="handle-del mr10" @click="handleExport">导出全部</el-button>
                <el-input v-model="query.postId" style="width: 100px" placeholder="岗位编号" class="handle-input mr10"></el-input>
                <el-input v-model="query.postName" placeholder="岗位名" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table
                :data="tableData"
                v-loading="loading"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="postId" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="deptName" label="所属部门" align="center"></el-table-column>
                <el-table-column prop="postName" label="岗位名" align="center"></el-table-column>
                <el-table-column label="基本薪资" align="center">
                    <template slot-scope="scope">￥{{ scope.row.salary }}</template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑 </el-button>
                        <el-button type="text" icon="el-icon-delete" class="red" @click="handleDelete(scope.$index, scope.row)"
                            >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="jumper,total, prev, pager, next, sizes"
                    @size-change="handleSizeChange"
                    :current-page.sync="query.pageIndex"
                    :page-sizes="[5, 10, 20, 30]"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 添加与编辑弹出框 -->
        <el-dialog :title="title" :visible.sync="open" width="30%" @close="cancel">
            <el-form ref="form" :model="form" :rules="rules" label-width="70px">
                <el-form-item label="岗位编号" v-if="title == '编辑岗位'">
                    <el-input v-model="form.postId" placeholder="请填写岗位编号"></el-input>
                </el-form-item>
                <el-form-item label="岗位名">
                    <el-input v-model="form.postName" placeholder="请填写岗位名称"></el-input>
                </el-form-item>
                <el-form-item label="部门">
                    <el-select placeholder="请选择部门" v-model="form.deptId" class="handle-select mr10">
                        <el-option v-for="dept in depts" :label="dept.deptName" :key="dept.deptId" :value="dept.deptId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="基本薪资">
                    <el-input type="number" v-model="form.salary" placeholder="请填写岗位基本薪资"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { listPost, delPost, addPost, updatePost, listDept, batchDelPost, exportPost,getPost} from '@/api/post';

export default {
    name: 'post',
    data() {
        return {
            query: {
                postName: '',
                pageIndex: 1,
                pageSize: 5,
                postId: undefined
            },
            tableData: [],
            loading: true,
            multipleSelection: [],
            delList: [],
            //是否显示弹出层
            open: false,
            //分页数据总条数
            pageTotal: 0,
            //弹出层form表单数据
            form: {},
            rules: {
                postName: [{ required: true, message: '岗位名称不能为空', trigger: 'blur' }],
                postId: [{ required: true, message: '岗位编码不能为空', trigger: 'blur' }],
                salary: [{ required: true, message: '岗位薪资不能为空', trigger: 'blur' }]
            },
            depts: {},
            title: '',
            idx: -1,
            id: -1
        };
    },
    created() {
        this.getData();
    },
    methods: {
        getData() {
            this.loading=true;
            listPost(this.query).then((res) => {
                const data = res.data;
                this.tableData = data.data;
                this.pageTotal = data.count;
                this.loading=false;
            });
        },
        getDepts(deptName) {
            const $this = this;
            listDept(deptName).then((res) => {
                $this.depts = res.data.data;
            });
        },
        // 触发搜索按钮
        handleSearch() {
            //重置页码
            this.query.pageIndex = 1;
            this.getData();
        },
        // 表单重置
        reset() {
            this.form = {
                postId: undefined,
                postName: undefined,
                salary: undefined,
                deptId: undefined
            };
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除该岗位吗？', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    const $this = this;
                    delPost(row.postId).then((res) => {
                        $this.$message.success('删除成功');
                        $this.getData();
                        $this.idx = index;
                    });
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                const postid = this.multipleSelection[i].postId;
                str += postid + ',';
            }
            const postIds = str.substring(0, str.lastIndexOf(','));
            // 二次确认删除
            this.$confirm(`确定要删除编号为(${postIds})岗位吗？`, '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    //删除最后一个逗号
                    const $this = this;
                    batchDelPost(postIds).then((res) => {
                        $this.$message.error(`删除了${postIds}`);
                        $this.multipleSelection = [];
                        $this.getData();
                    });
                })
                .catch(() => {});
        },
        // 添加操作
        handleAdd() {
            this.title = '添加岗位';
            this.open = true;
            this.getDepts('');
        },
        // 编辑操作
        handleEdit(index, row) {
            this.title = '编辑岗位';
            this.getDepts(row.deptName);
            this.idx = index;
            getPost(row.postId).then((res)=>{
                this.form = res.data;
            })
            this.open = true;
        },
        // 提交按钮
        submitForm: function () {
            const $this = this;
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (this.form.postId != undefined) {
                        updatePost(this.form).then((response) => {
                            $this.$message.success('修改成功');
                            $this.getData();
                            $this.cancel();
                        });
                    } else {
                        addPost(this.form).then((response) => {
                            $this.$message.success('添加成功');
                            $this.getData();
                            $this.cancel();
                        });
                    }
                }
            });
        },
        //取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 分页导航
        handlePageChange() {
            this.getData();
        },
        handleSizeChange(val) {
            this.query.pageSize = val;
            this.getData();
        },
        downloadFile(data, fileName) {
            if (!data) {
                return;
            }
            const link = document.createElement('a');
            let blob = new Blob([data], { type: 'application/vnd.ms-excel' });
            link.style.display = 'none';
            link.href = URL.createObjectURL(blob);

            link.setAttribute('download', fileName + '.xls');
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        },
        handleExport() {
            this.$confirm('是否确认导出所有岗位数据项?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(function () {
                    return exportPost();
                })
                .then((response) => {
                    this.downloadFile(response, '岗位表');
                });
        }
    }
};
</script>

<style scoped>
body {
    margin: 0;
}
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.red {
    color: #ff0000;
}

.mr10 {
    margin-right: 10px;
}

.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
